<?php

namespace Home\Controller; 
use Think\Controller;

//用户中心全局控制
class LoginController extends  Controller { 
    


    
    //登录页面
    public  function  login(){
    	$type= isset($_GET['type'])?$_GET['type']:0;
    	$this->assign("type",$type);
		$this->assign("pagetitle","51M登录");
    	$this->display();
    }

	
    //登陆操作
    public  function UserLogin(){
		extract($_POST);


		//$this->opensession= (array)session("openid");
		/* $openid=$this->opensession['openid']['openid'];
		$user=M("wx_binduser")->where(array("openid" => $openid))->field("user_id")->find();
		
		//绑定过的，直接登陆
		if($user)
		{
			
			unset($_SESSION['openid']);
			$user_name=M("Users")->where(array("user_id" => $user['user_id']))->find();
			$this->opensession['openid']['user']=$user_name;
			//$open['user']=$user_name;
			//$open['openid']=$openid;
			//$open['wxconfig']=$this->opensession['openid']['wxconfig'];
			session('openid',$this->opensession['openid']);
			//构建51M的session
			$_SESSION['user_id']     = $user['user_id'];
            $_SESSION['user_name']   = $user_name['user_name'];
			$ret=array("status"=>1,"message"=>"51M登陆成功！");
			$this->ajaxReturn ($ret);
			exit;
		} */
		   
		 $wheres['user_name|mobile_phone']=$user_name; 
		 $result=M("Users")->where($wheres)->find();
		if(empty($result))
		{
			$ret=array("status"=>0,"message"=>"用户名错误！");
			$this->ajaxReturn ($ret);
			exit;
		}
		
		$passwd=md5(md5($password).$result['ec_salt']);		
		if($result['password'] !=$passwd)
		{
			$ret=array("status"=>0,"message"=>"密码错误！");
			$this->ajaxReturn ($ret);
			exit;
		}
		/* //添加绑定操作
		if($openid)
		{
			
			$data['user_id']=$result['user_id'];
			$data['openid']=$openid;
			$data['bindtype']="user";
			$data['createtime']=date("Y-m-d H:i:s",time());
			$user=M("wx_binduser")->add($data);
			unset($_SESSION['openid']);
			$this->opensession['openid']['user']=$result;
			//$open['openid']=$openid;
			//$open['wxconfig']=$this->opensession['openid']['wxconfig'];
			session('openid', $this->opensession['openid']);
		} */
		
	  //构建cookie
	  if($_cookie[C('COOKIE_PREFIX').'userCookie'])
		    {
			//删除cookie
	        cookie ("userCookie", "", time() - 3600);
		    }
	    $cookieName="userCookie";
	    $cookieValue['userCookie']=base64_encode("51M@".$result['user_id']."@".C("KEY"));
	    cookie($cookieName,json_encode($cookieValue), C("COOKIE_TIME"));
	  //构建51M的session;
	    $_SESSION['user_id']     = $result['user_id'];
        $_SESSION['user_name']   = $user_name;
		
		$ret=array("status"=>1,"message"=>"51M登录成功！");
		$this->ajaxReturn ($ret);
		exit;
    	
    }
    //注册页面
    public function registeruser(){
		$this->assign("pagetitle","51M注册");
    	$this->display();
    }

    //获取短信验证码
   public function UserRegister_code(){
   	    //验证用户名是否注册
        $where['user_name|mobile_phone']=$user_name;
		$result=M("Users")->where($where)->getField("user_id");
		if($result)
		{
			$ret=array("code"=>0,"msg"=>"该用户已注册");
			$this->ajaxReturn ($ret);
			exit;
		}
     $data['mobile'] = $_POST['mobile'];
      $data['mobile_code'] = $this->random(4,1);
     //保存session
     $arrlist = $data; 
     $_SESSION['mobile'] = $arrlist;
    
     //请求mobile/smsmessage_au.php
     $url=C("WEBURL")."/mobile/smsmessage_au.php?act=send_register";
     //添加个参数区分需不需要构建session
     $data['status'] = 1;
     $list= $this->http_request($url,$data);
     echo $list;
     exit;
   }

   //日志记录
   protected function logger($log_content)
   {
   	if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
   		sae_set_display_errors(false);
   		sae_debug($log_content);
   		sae_set_display_errors(true);
   	}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
   		$max_size = 10000;
   		$log_filename = "log.xml";
   		$dir         =  dirname($log_filename);
   		if(!is_dir($dir)){
   			mkdir($dir,0777,true);
   		}
   		if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
   		file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
   	}
   }




    //注册处理
    public function UserRegister(){
    	extract($_POST);
		$where['user_name|mobile_phone']=$user_name;
		$result=M("Users")->where($where)->getField("user_id");
		if($result)
		{
			$ret=array("status"=>0,"message"=>"该用户已存在");
			$this->ajaxReturn ($ret);
			exit;
		}

        if (strlen($code)<=0) {
           	$ret=array("status"=>0,"message"=>"请输入手机验证码");
			$this->ajaxReturn ($ret);
			exit;
        }
        $arr_session = (array)$_SESSION['mobile'];
        $session_mb=isset($arr_session['mobile'])?$arr_session['mobile']:"";
        $session_mobile_code=isset($arr_session['mobile_code'])?$arr_session['mobile_code']:"";
        //验证码
        if ($user_name != $session_mb || $code !=$session_mobile_code) {
            $ret=array("status"=>0,"message"=>"手机验证码错误");
			$this->ajaxReturn ($ret);
			exit;
        }

		$ec_salt=rand(1,9999);
		//$openid=$this->opensession['openid']['openid'];
		$data['user_name']=$user_name;
		$data['password']=md5(md5($password).$ec_salt);
		$data['mobile_phone']=$user_name;
		$data['ec_salt']=strval($ec_salt);
		$data['reg_time']=time();
		$data['flag']=11;
		$data['email']="";
		$data['alias']="";
		$data['question']="";
		$data['answer']="";
		$data['sex']=0;
		$data['birthday']="0000-00-00";
		$data['user_money']=0;
		$data['frozen_money']=0;
		$data['pay_points']=0;
		$data['rank_points']=0;
		$data['address_id']=0;
		$data['last_login']=time();
		$data['last_time']=date("Y-m-d H:i:s",time());
		$data['vip_addtime']=date("Y-m-d H:i:s",time());
		$data['msn']="";
		$data['remark']="";
		$data['last_ip']="";
		$data['visit_count']=0;
		$data['user_rank']=0;
		$data['is_special']=0;
		$data['parent_id']=0;
		$data['salt']=0;
		$data['qq']="";
		$data['office_phone']="";
		$data['home_phone']="";
		$data['credit_line']=0;
		$data['is_validated']=0;
		$data['voucher_money']=0;
		$data['Openid']="";
		$data['Headimgurl']="";
		$data['Unionid']="";
		$data['Remark']="";
		$data['subscribe_time']=time();
		$data['nickname']="";
		$result=M("Users")->add($data);
		if($result)
		{
			/* //添加绑定操作
			if($openid)
			{
				$data['user_id']=$result;
				$datab['user_id']=$result;
				$datab['openid']=$openid;
				$datab['bindtype']="User";
				$datab['createtime']=date("Y-m-d H:i:s",time());
				$user=M("wx_binduser")->add($datab);
				unset($_SESSION['openid']);
				$this->opensession['openid']['user']=$data;
				//$open['user']=$data;
				//$open['openid']=$openid;
				//$open['wxconfig']=$this->opensession['openid']['wxconfig'];
				session('openid',$this->opensession['openid']);
			} */
			//添加绑定操作
			//C("").$result;
			if($_cookie[C('COOKIE_PREFIX').'userCookie'])
		    {
			//删除cookie
	        cookie ("userCookie", "", time() - 3600);
		    }
			$cookieName="userCookie";
	        $cookieValue['userCookie']=base64_encode("51M@".$result."@".C("KEY"));
	        cookie($cookieName,json_encode($cookieValue), C("COOKIE_TIME"));
		    //构建51M的session;
			$_SESSION['user_id']     = $result;
			$_SESSION['user_name']   = $user_name;
			$ret=array("status"=>1,"message"=>"51M登录成功！");
			$this->ajaxReturn ($ret);
			exit;
		}
		else
		{
			$ret=array("status"=>0,"message"=>"操作失败！");
			$this->ajaxReturn ($ret);
			exit;
		}
		
    }

    //生成随机数
function random($length = 6 , $numeric = 0) {
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    if($numeric) {
        $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
    } else {
        $hash = '';
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
    }
    return $hash;
}

    //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
    public function http_request($url, $data = null){
    	$curl = curl_init();
    	curl_setopt($curl, CURLOPT_URL, $url);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    	if (!empty($data)){
    		curl_setopt($curl, CURLOPT_POST, 1);
    		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    	}
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    	$output = curl_exec($curl);
    	$errinfo=curl_getinfo($ch);
    	curl_close($curl);
    	return $output;
    }
}
?>
